package com.scholarship.modules.student.service;

import com.scholarship.modules.admin.service.FeedbackListService;
import com.scholarship.modules.login.dto.LoginInfoDto;
import com.scholarship.modules.student.dto.MajorInfoDto;
import com.scholarship.modules.student.dto.NApplicationDto.*;
import com.scholarship.modules.student.entity.*;
import com.scholarship.modules.student.exce.ErrorException;
import com.scholarship.modules.student.exce.GetSQLException;
import com.scholarship.modules.student.exce.UpdateSQLException;
import com.scholarship.modules.student.exce.UserException;
import com.scholarship.modules.student.mapper.NStuApplicationMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: huanghao
 * @date: 2021/7/22 14:22
 * @description:
 * @modifiedBy:
 */

/*
* 整体说明：A、B、C称父类奖项
*           A1、A2、B1、C1、C2这样的称为子类奖项
*           子类奖项中的各个组件称为子类奖项的表项
*           以 子类奖项a3为例，a3是专业证书，属于A类父类奖项
*           其中的证书名称、证书等级、发证机构名称等为表项
* */

@Service
public class NStuApplicationService {
    private Integer selectId = 4;
    private Integer attributeIdOfInt = 1;
    private Integer attributeIdOfDecimal = 2;

    @Autowired
    NStuApplicationMapper stuApplicationMapper;
    @Autowired
    private FeedbackListService feedbackListService;

    //获取申请表所有表项（父类 + 子类）
    public List<RewardTypeDto> getApplicationItemList() {
        //获取父类表项
        List<RewardTypeDto> fatherItemList = stuApplicationMapper.listRewardTypes();
        List<SonRewardDetailEntity> sonItemList = stuApplicationMapper.listRewardTypeDetails();
        for (int i = 0; i < fatherItemList.size(); i++) {
            List<SonRewardDetailEntity> tmpList = new ArrayList<SonRewardDetailEntity>();
            int id = fatherItemList.get(i).getId();
            for (int j = 0; j < sonItemList.size(); j++) {
                SonRewardDetailEntity tmpDetailDto = sonItemList.get(j);
                if(tmpDetailDto.getTypeId() == id)
                    tmpList.add(tmpDetailDto);
            }
//            fatherItemList.get(i).setDetailList(tmpList);
        }
        return fatherItemList;
    }

    //获取父类+子类+表项整体结构信息
    public List<RewardTypeDto> getApplicationTableInfo() {
        List<RewardTypeDto> fatherItemList = stuApplicationMapper.listRewardTypes();
        List<SonRewardDetailEntity> sonItemList = stuApplicationMapper.listRewardTypeDetails();
        for (RewardTypeDto tmpFatherItem : fatherItemList) {
            //遍历父类奖项信息
            List<RewardTypeDetailDto> tmpList = new ArrayList<RewardTypeDetailDto>();
            int tmpFatherRewardId = tmpFatherItem.getId();
            for (SonRewardDetailEntity tmpSonRewardItem : sonItemList) {
                //遍历子类奖项信息，与对应父类奖项匹配
                if (tmpSonRewardItem.getTypeId() == tmpFatherRewardId){
                    //匹配成功，则填入信息
                    RewardTypeDetailDto tmp = new RewardTypeDetailDto();
                    tmp.setId(tmpSonRewardItem.getId());
                    tmp.setName(tmpSonRewardItem.getName());
                    tmp.setScore(tmpSonRewardItem.getScore());
                    tmp.setTableName(tmpSonRewardItem.getTableName());
//                    tmp.setDetail(tmpSonRewardItem.getDetail());
                    if (tmpSonRewardItem.getIsUploadFile() == null)
                        tmp.setIsUploadFile(false);
                    else
                        tmp.setIsUploadFile((tmpSonRewardItem.getIsUploadFile()==1) ? true : false);
                    if (tmpSonRewardItem.getIsImport() == null)
                        tmp.setIsImport(null);
                    else
                        tmp.setIsImport((tmpSonRewardItem.getIsImport()==1) ? true : false);
                    List<TableItem> tmpTableItemList = stuApplicationMapper.listTableItemsByTableId(tmp.getId());
//                    tmp.setTableItemList();
                    if (tmpTableItemList != null && tmpTableItemList.size() > 0) {
                        List<TableItemDto> tableItemDtoList = new ArrayList<TableItemDto>();
                        //构造表项信息
                        for (int i = 0; i < tmpTableItemList.size(); i++) {
                            TableItem tmpItem = tmpTableItemList.get(i);
                            List<DropdownItemDto> dropdownItemStringList = new ArrayList<DropdownItemDto>();
                            if (tmpItem.getFieldId() == selectId){
                                List<DropdownItem> dropdownItemsList = stuApplicationMapper.listDropdownItemsByFieldId(tmpItem.getId());
                                for (DropdownItem dropdownItem : dropdownItemsList)
                                    dropdownItemStringList.add(new DropdownItemDto(dropdownItem.getId(), dropdownItem.getOptionName()));
                            }
                            if (dropdownItemStringList.size() <= 0)
                                dropdownItemStringList = null;
                            tableItemDtoList.add(new TableItemDto(tmpItem.getItemName(), tmpItem.getAttributeName(), tmpItem.getFieldId(), tmpItem.getIsTeacherWrite(), dropdownItemStringList, null));
                        }
                        tmp.setTableItemList(tableItemDtoList);
                    }
                    tmpList.add(tmp);
                }
            }
            tmpFatherItem.setSonRewardList(tmpList);
        }
        return fatherItemList;
    }


    //获取子类奖项的结构信息
    public RewardStructureDto getItemStructure(RewardInfoDto rewardInfo) {
        List<TableItem> tableItemList = stuApplicationMapper.listTableItemsByTableId(rewardInfo.getId());
        RewardStructureDto rewardStructure = new RewardStructureDto();
        rewardStructure.setTableId(rewardInfo.getId());
        rewardStructure.setIsUploadFile(rewardInfo.getIsUploadFile());
        rewardStructure.setIsImport(rewardInfo.getIsImport());
        rewardStructure.setTableItemList(tableItemList);

        for (int i = 0; i < tableItemList.size(); i++) {
            TableItem tmpItem = tableItemList.get(i);
            tmpItem.setDropdownItemList(null);
            if (tmpItem.getFieldId() == selectId){
                List<DropdownItem> dropdownItemsList = stuApplicationMapper.listDropdownItemsByFieldId(tmpItem.getId());
                System.out.println(tmpItem.getId());
                tmpItem.setDropdownItemList(dropdownItemsList);
            }
        }
        return rewardStructure;
    }

    //处理、保存子类奖项的详细信息
    public void saveRewardRecord(RewardSubmitDto rewardSubmitDto) throws Exception{
        //目前已知问题：如果有字段为空，那么会报错
        String userId = rewardSubmitDto.getUserId();
        String tableName = rewardSubmitDto.getTableName();

        //判断文件上传路径为空
//        if (rewardSubmitDto.getIsUploadFile().equals(1) && (rewardSubmitDto.getValue() == null || rewardSubmitDto.getValue().equals(""))) {
//            throw new ErrorException("需要上传文件，但文件路径为空");
//        }
        List<SubmitTableItem> submitTableItemList = rewardSubmitDto.getSubmitTableItemList();
        int empty = 0;
        for (int i = 0; i < submitTableItemList.size(); i++) {
            SubmitTableItem tmp = submitTableItemList.get(i);
            if (tmp.getIsTeacherWrite().equals(0) && (tmp.getValue() == null || tmp.getValue().equals(""))) {
                System.out.println(tmp.getAttributeName());
                empty++;
            }
        }
        if (empty > 0) {
            System.out.println(empty);
            System.out.println(submitTableItemList.size());
            throw new ErrorException("表单存在空值");
        }

        try {
            //向对应子类奖项表插入记录
            stuApplicationMapper.insertRewardTableByRewardSubmitDto(rewardSubmitDto);

            if (rewardSubmitDto.getIsUploadFile().equals(1) && rewardSubmitDto.getValue() != null) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                String year = df.format(new Date());
                rewardSubmitDto.setImportYear(year);
                //向t_reward_application表插入记录
                stuApplicationMapper.insertRewardApplicationByRewardSubmitDto(rewardSubmitDto);
            }

            //向t_reward_feedback表插入记录
//            stuApplicationMapper.insertRewardFeedbackByReward(rewardSubmitDto);

            /* 这个地方关于分数的计算可能有问题，要再考虑下 */
//            Float score = new Float(0);
//            List<SubmitTableItem> submitTableItemList = rewardSubmitDto.getSubmitTableItemList();
//            for (int i = 0; i < submitTableItemList.size(); i++) {
//                SubmitTableItem tmpItem = submitTableItemList.get(i);
//                Boolean isNumber = tmpItem.getValue().matches("-?[0-9]+.？[0-9]*");
//                if (isNumber == true) {
//                    score = Float.parseFloat(tmpItem.getValue());
//                    break;
//                }
//            }
            //更新学生预估分信息
//            stuApplicationMapper.updateStuRatingOfRwardFeedback(rewardSubmitDto.getUserId(), score);
        }
        catch (Exception e) {
            throw e;
        }
    }

    //获取某个学生所有的子类奖项申请情况
    public StuRewardApplicationDto getStudentRewardRecord(String userId) {
        List<StuApplicationViewEntity> viewItemList =  stuApplicationMapper.listStuendApplicationRecordByUserId(userId);
        Map<Integer, String> sonTableMap = new HashMap<Integer, String>();
        StuRewardApplicationDto stuRewardApplicationDto = new StuRewardApplicationDto(userId, new ArrayList<FatherReward>());
        for (StuApplicationViewEntity item : viewItemList) {
            sonTableMap.put(item.getSonId(), item.getSonTableName());
        }
        System.out.println(sonTableMap.size() + "  sonTableMap size");
        for (Map.Entry<Integer, String> entry : sonTableMap.entrySet()) {
            System.out.println("entry key : " + entry.getKey() + "   entry value : " + entry.getValue());
        }
        return new StuRewardApplicationDto();
    }

    //获取学生奖学金申请状态
    public Integer getStuApplicationState(String userId) throws Exception{
        Integer stuState = stuApplicationMapper.getStuApplicationState(userId);
        if (stuState == null) {
            throw new UserException("该用户不存在");
        }
        return stuState;
    }

    //取消学生奖学金申请状态
    public void cancelStuApplicationState(String userId) throws Exception{
        Integer deleteResult = stuApplicationMapper.deleteStuFeedbackRecord(userId);
        if (deleteResult <= 0)
            throw new UserException("该用户不存在奖学金申请记录");
    }

    //提交学生奖学金申请信息并修改状态
    public void submitApplication(String userId) throws Exception{
        try {
            RewardSubmitDto rewardSubmitDto = new RewardSubmitDto();
            rewardSubmitDto.setUserId(userId);
            stuApplicationMapper.insertRewardFeedbackByReward(rewardSubmitDto);
            //审核中--3
            int result = stuApplicationMapper.updateStuApplicationState(userId, 3);
            if (result <= 0) {
                throw new UpdateSQLException("无法更改学生奖学金申请提交状态");
            }
        }
        catch (Exception e) {
//            stuApplicationMapper.updateStuApplicationState(userId, 0);
            throw e;
        }
    }

    //判断是否允许学生提交奖学金申请
    public boolean checkSubmitTime() throws Exception {
        ApplicationTime applicationTime = stuApplicationMapper.getStuAppicationTime();
        if (applicationTime == null || applicationTime.getSubmitStartTime().equals("") || applicationTime.getSubmitEndTime().equals("")) {
            throw new GetSQLException("获取申请时间范围出错");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date currentTime = df.parse(df.format(new Date()));
        Date startTime = df.parse(applicationTime.getSubmitStartTime());
        Date endTime = df.parse(applicationTime.getSubmitEndTime());
//        System.out.println("current time : " + df.format(currentTime) + "   " + currentTime.getTime());
//        System.out.println("start time : " + df.format(startTime) + "   " + startTime.getTime());
//        System.out.println("end time : " + df.format(endTime) + "   " + endTime.getTime());
        if (currentTime.before(startTime) || currentTime.after(endTime)) {
            return false;
        }
        return true;
    }

    //保存学生某个奖项信息
//    public boolean saveSpecificSonReward(String userId, com.scholarship.modules.admin.dto.RewardTypeDetailDto rewardTypeDetailDto) throws Exception{
//
//    }

    //测试
    public void hhText() {
        MyEntity myEntity = stuApplicationMapper.testFunc(1);
        System.out.println(myEntity);
        System.out.println(myEntity.getTypeName());
        System.out.println(myEntity.getPercent());
        System.out.println(myEntity.getTopScore());
    }

}
